﻿using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace Magellan.ProjectWizards.Manager
{
    public partial class ProgressDialog : Form
    {
        private readonly Action _backgroundTask;

        private ProgressDialog(Action backgroundTask)
        {
            _backgroundTask = backgroundTask;
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var worker = new BackgroundWorker();
            worker.DoWork += (x, y) => _backgroundTask();
            worker.RunWorkerCompleted += (x, y) => TaskCompleted(y.Error);
            worker.RunWorkerAsync();
        }

        private void TaskCompleted(Exception error)
        {
            if (error != null)
            {
                MessageBox.Show(error.Message, "Magellan Setup", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Close();
        }

        public static void Show(string caption, Action backgroundTask)
        {
            var dialog = new ProgressDialog(backgroundTask);
            dialog.Text = caption;
            dialog.ShowDialog();
        }
    }
}
